import { defineStore, acceptHMRUpdate } from "pinia";
import { invokeAsyncAPi, invokeAPi } from "@/xz-fn";

const formatMerchant = (id: string) => {
  const merchantMap = {
    '3448045082': '360',
    'lxoem': 'lx'
  }
  const target = merchantMap[id as keyof typeof merchantMap]
  console.log('merchant_id：', id, ' 渠道：', target)
  return target || ''
}

export const systemAppStore = defineStore({
  id: "system",
  state: () => ({
    appInfo: {
      appID: import.meta.env.VITE_APP_APPID, // 客户端id
      channel: "", // 渠道信息
      uuid: "", // 设备信息
      device_name: "", // 设备名称
      version: "1.0.0.0", // 版本号
      allPackages: [import.meta.env.VITE_APP_PKGID],
      merchantId: import.meta.env.VITE_APP_MERCHANTID, // 主体id
      projectId: "",
      installDate: "",
      merchant: ''
    },
    showEngine: true,
    pubkey: "",
    appCfg: {
      site: import.meta.env.VITE_APP_ORIGIN,
      name: import.meta.env.VITE_APP_NAME,
      logo: import.meta.env.VITE_APP_LOGO
    }
  }),
  actions: {
    getDeviceInfo() {
      return invokeAsyncAPi("fq_GetClientInfo").then(async (deviceInfo: any) => {
        this.appInfo.appID = deviceInfo.app_id + "";
        this.appInfo.channel = deviceInfo.union_id + ""; // 后端接口需要字符类型
        this.appInfo.uuid = deviceInfo.pcid;
        this.appInfo.device_name = deviceInfo.device_name;
        this.appInfo.version = deviceInfo.version || "1.0.2.2";
        this.appInfo.merchantId = deviceInfo.merchant_id;
        this.appInfo.projectId = deviceInfo.project_id;
        this.appInfo.merchant = formatMerchant(invokeAPi('xz_get_merchant_Id'))

        if (['lx'].includes(this.appInfo.merchant)) {
          this.showEngine = false
        }

        const install_time = deviceInfo.install_time * 1000
        if(install_time){
          // @ts-ignore
          this.appInfo.installDate = new Date(install_time).toGMTString()
        }
      });
    }
  }
});
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(systemAppStore, import.meta.hot));
}
